//
//  MeetingView.swift
//  codelabs
//
//  Created by 雷雷 on 25/05/2025.
//

import SwiftUI
import SwiftData
import TimerKit
import AVFoundation

struct MeetingView: View {
    let scrum:DailyScrum
    
    @State var timer:ScrumTimer = ScrumTimer()
    
    @Binding var errorWrapper:ErrorWrapper?
    
    @Environment(\.modelContext) private var context
    @Environment(\.dismiss) private var dismiss
    
    @State var doneMeeting:Bool = false
    
    private let player = AVPlayer.dingPlayer()
    
    private var allDoneSpeakers:[ScrumTimer.Speaker]{
        timer.speakers.map{ScrumTimer.Speaker(name:$0.name,isCompleted: true)}
    }
    
    var body: some View {
        
        ZStack {
            RoundedRectangle(cornerRadius:16.0)
                .fill(scrum.theme.mainColor)
            
            VStack{
                
                if doneMeeting{
                    MeetingProgressView(
                        secondElasped: scrum.lengthInMinutes * 60,
                        secondRemaining: 0, theme: scrum.theme
                    )
                    
                    Spacer()
                    
                    MeetingTimerView(
                        speakers: allDoneSpeakers,
                        theme: scrum.theme)
                    
                    Spacer()
                    
                    MeetingFooterView(
                        speakers: allDoneSpeakers,
                        startAction: {
                            timer=ScrumTimer()
                            startScrum()
                        },
                        skipAction: timer.skipSpeaker,doneAction: {                            doneScrum()
                        },
                        doneMeeting:$doneMeeting)
                    
                    
                }else{
                   
                    MeetingProgressView(
                        secondElasped: timer.secondsElapsed, secondRemaining: timer.secondsRemaining, theme: scrum.theme
                    )
                    
                    Spacer()
                    
                    MeetingTimerView(speakers: timer.speakers, theme: scrum.theme)
                    
                    
                    Spacer()
                    
                    MeetingFooterView(
                        speakers: timer.speakers,
                        startAction: {
                            startScrum()
                        },
                        skipAction: timer.skipSpeaker,doneAction: {
                            timer.skipSpeaker()
                            
                            do{
                               try endScrum()
                            }catch{
                                errorWrapper=ErrorWrapper(error:error,
                                                          guidance: "Faled to end scrum")
                            }
                        },
                        doneMeeting:$doneMeeting)
                }
              
                
            }
            .padding()
            
        }
        .padding()
        .foregroundColor(scrum.theme.accentColor)
        .navigationBarTitleDisplayMode(.inline)
        .onAppear{
            startScrum()
        }
        .onDisappear{
            do{
                try endScrum()
            }catch{
                errorWrapper = ErrorWrapper(error: error, guidance: "Meeting time was not recorded. Try again later.")
            }
        }
        .navigationTitle(scrum.title)
        
    }
    
    func startScrum(){
        timer.reset(lengthInMinutes: scrum.lengthInMinutes, attendeeNames: scrum.attendees.map{$0.name})
        timer.speakerChangedAction={
            player.seek(to: .zero)
            player.play()
        }
        timer.startScrum()
    }
    
    
    func doneScrum(){
        player.pause()
        timer.stopScrum()
    }
    
    func endScrum() throws{
        doneScrum()
        let history = ScrumHistory(attendees:scrum.attendees)
        scrum.history.insert(history, at: 0)
        try context.save()
    }
}

#Preview(traits: .dailyScrumSampleData) {
    @Previewable @Query(sort:\DailyScrum.title) var scrums:[DailyScrum]
    @Previewable @State var errorWrapper: ErrorWrapper? = ErrorWrapper(
        error:SampleError.errorRequired,
        guidance:"You can safely ingnonr this error."
    )
    
    NavigationStack {
        MeetingView(scrum:scrums[0],errorWrapper: $errorWrapper)
    }
}
